import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElIcon,
  ElSpace,
  ElLink,
  ElPopover,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import type { FormValuesType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { fnStateEnum, facilitiesStateEnum } from '~/store/monitor/typings'

import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import AlarmQuery from './alarmQuery'
import ExportExcel from '~/components/ExportExcel'
import styles from '../index.module.scss'
import ColorfulBadge from '~/components/ColorfulBadge'

export default defineComponent(function Equipment() {
  const store = useStore()
  const router = useRouter()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<FormValuesType>({})
  const equipmentState = useVuexGetters('equipment', [
    'equipmentBrandOpt',
    'equipmentModelOpt',
    'fnStateOpt',
    'fnStateEnum',
    'communicationStateOpt',
    'communicationStateEnum',
    'facilitiesStateOpt',
    'classificationStateOpt'
  ])
  const state = reactive({
    exportVisible: false,
    visible: false,
    deviceId: ''
  })
  const userState = useVuexGetters('user', ['permission'])
  const columns: TableColumnProps<FormValuesType>[] = [
    {
      label: '设备名称',
      prop: 'name',
      minWidth: 200,
      fixed: 'left',
      unFixed: true,
      showOverflowTooltip: true,
      sortable: true,
      disabled: true
    },
    {
      label: '设备编号',
      prop: 'code',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '设备品牌',
      prop: 'brandName',
      minWidth: 160,

      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '设备型号',
      prop: 'modelName',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '通信状态',
      prop: 'onlineState',
      minWidth: 160,
      showOverflowTooltip: true,
      enumValues: equipmentState.communicationStateEnum,
      sortable: true,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={option.row.onlineState as number}
          options={{ success: 1, info: 0, warning: 2 }}
        />
      )
    },
    {
      label: '故障状态',
      prop: 'runStatus',
      minWidth: 160,
      showOverflowTooltip: true,
      enumValues: equipmentState.fnStateEnum,
      sortable: true,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={option.row.runStatus as number}
          options={{ success: 1, info: 0, warning: 2 }}
        />
      )
    },
    {
      label: '更新时间',
      prop: 'updateTime',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '设备分类',
      prop: 'categoryName',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '所属设施',
      prop: 'distributionName',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '投运状态',
      prop: 'useStatus',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true,
      render: (_, value) => {
        return <>{value === 0 ? '未投运' : '已投运'}</>
      }
    },
    {
      label: '投运日期',
      prop: 'deliverDate',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '所属区域',
      prop: 'areaName',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '备注',
      prop: 'memo',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 280,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      disabled: true,
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('monitor_device_update') && (
            <ElLink type="primary" onClick={() => editOpen(row)}>
              <AliIcon type="icon-bianji" />
              &nbsp; 编辑
            </ElLink>
          )}
          {userState.permission.value.has('monitor_device_remove') && (
            <ElLink type="primary" onClick={() => del(row)}>
              <AliIcon type="icon-shanchu" />
              &nbsp; 删除
            </ElLink>
          )}
          <ElPopover
            style="width:80px"
            trigger="click"
            v-slots={{
              reference: () =>
                userState.permission.value.has('monitor_police_data') && (
                  <ElLink type="primary">
                    <AliIcon type="icon-gengduo1" />
                    &nbsp; 更多
                  </ElLink>
                )
            }}
          >
            <ElLink type="primary" onClick={() => alarmQuery(row)}>
              <AliIcon type="icon-jingbaochaxun1" />
              &nbsp; 警报查询
            </ElLink>
          </ElPopover>
        </ElSpace>
      )
    }
  ]

  onMounted(() => {
    //  设备品牌
    store.dispatch('equipment/GetTenantBrandList')
    //  设备型号
    store.dispatch('equipment/GetTenantModelList')
    //  设备分类
    store.dispatch('equipment/GetNodeByParentCode')
    //  所属设施
    store.dispatch('equipment/SelectBoxListByKey')
    //  通信状态
    store.dispatch('equipment/FnStateGet', { code: 'runStatus' })
    //  运行状态
    store.dispatch('equipment/CommunicationStateGet', { code: 'onlineStatus' })
  })
  //  新增
  const open = (type: string) => {
    router.push({ path: '/monitor/equipment/addEdit', query: { type } })
  }
  //  编辑
  const editOpen = (row: any) => {
    router.push({ path: '/monitor/equipment/addEdit', query: { type: 'edit', id: row.id } })
  }
  //  删除
  const del = (row: any) => {
    const ids = row.id
    delAjax(ids, true)
  }
  //  删除多个
  const delMultiple = () => {
    const ids = proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    if (!ids) {
      ElMessage({ type: 'warning', message: '请勾选数据' })
      return
    }
    delAjax(ids, false)
  }
  //  删除请求
  const delAjax = (ids: any, value: boolean) => {
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {value && <p class="delete-title">确认删除数据?</p>}
          {!value && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认删除选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认删除选中数据？'}
            </p>
          )}
          <p class="delete-content">删除后不可恢复，是否确认删除。</p>
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    }).then(async () => {
      const { code } = await store.dispatch('equipment/DeviceRemove', { ids })
      if (code === 200) {
        proSaasTableRef.value!?.clearSelection?.()
        proSaasTableRef.value!?.toSearch()
        ElMessage({ type: 'success', message: '操作成功' })
      }
    })
  }
  //  报警查询
  const alarmQuery = (row: any) => {
    state.deviceId = row.id
    state.visible = !state.visible
  }
  //  关闭报警查询
  const cancel = () => {
    state.visible = !state.visible
  }
  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') {
      if (formValues.keyWord!?.length < 3) {
        ElMessage.error('关键字输入太少，无法匹配到有效数据')
        return
      }
      proSaasTableRef.value!?.toSearch()
    }
  }
  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }
  // 打开导出弹框
  const handleChangeExportModal = () => {
    state.exportVisible = !state.exportVisible
  }

  return () => (
    <ElCard>
      <ProSaasTable<FormValuesType>
        tableId="monitor_equipment_index"
        ref={proSaasTableRef}
        columns={columns}
        searchParams={formValues}
        hasSelection
        dispatchType="equipment/DeviceListGet"
        searchFormProps={{
          model: formValues
        }}
        headerTitle={
          <>
            {userState.permission.value.has('monitor_device_add') && (
              <ElButton type="primary" onClick={() => open('add')}>
                <ElIcon>
                  <Plus />
                </ElIcon>
                &nbsp; 新增
              </ElButton>
            )}
            {userState.permission.value.has('monitor_device_remove') && (
              <ElButton type="danger" onClick={delMultiple}>
                <AliIcon type="icon-shanchu" />
                &nbsp; 删除
              </ElButton>
            )}
            {userState.permission.value.has('monitor_device_export') && (
              <ElButton type="success" onClick={handleChangeExportModal}>
                <AliIcon type="icon-daochu" />
                &nbsp; 导出
              </ElButton>
            )}
          </>
        }
        searchformResponsiveCol={[
          <ElFormItem key="keyWord" prop="keyWord" label="">
            <ElInput
              v-model={formValues.keyWord}
              placeholder="设备名称或编号"
              clearable
              onKeydown={handleKeyDownEnterSubmitForm}
              onClear={clearSearchTable}
            />
          </ElFormItem>,
          <ElFormItem key="brandId" prop="brandId">
            <ElSelect
              v-model={formValues.brandId}
              filterable
              clearable
              placeholder="设备品牌"
              onChange={clearSearchTable}
            >
              {equipmentState.equipmentBrandOpt?.value?.map((item: facilitiesStateEnum) => (
                <ElOption key={item?.id} label={item?.name} value={item?.id} />
              ))}
            </ElSelect>
          </ElFormItem>,
          <ElFormItem key="modelId" prop="modelId">
            <ElSelect
              v-model={formValues.modelId}
              filterable
              clearable
              placeholder="设备型号"
              onChange={clearSearchTable}
            >
              {equipmentState.equipmentModelOpt?.value?.map((item: facilitiesStateEnum) => (
                <ElOption key={item?.id} label={item?.name} value={item?.id} />
              ))}
            </ElSelect>
          </ElFormItem>,
          <ElFormItem key="onlineState" prop="onlineState">
            <ElSelect
              v-model={formValues.onlineState}
              clearable
              placeholder="通信状态"
              onChange={clearSearchTable}
            >
              {equipmentState.communicationStateOpt?.value?.map((item: fnStateEnum) => (
                <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
              ))}
            </ElSelect>
          </ElFormItem>,
          <ElFormItem key="runStatus" prop="runStatus">
            <ElSelect
              v-model={formValues.runStatus}
              clearable
              placeholder="故障状态"
              onChange={clearSearchTable}
            >
              {equipmentState.fnStateOpt?.value?.map((item: fnStateEnum) => (
                <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
              ))}
            </ElSelect>
          </ElFormItem>
        ]}
      />
      {state.visible && (
        <AlarmQuery visible={state.visible} deviceId={state.deviceId} cancel={cancel} />
      )}
      {state.exportVisible && (
        <ExportExcel
          visible={state.exportVisible}
          dispatchType="equipment/DeviceExport"
          columns={proSaasTableRef.value?.filterColumns}
          payload={{ params: formValues }}
          onCancel={handleChangeExportModal}
        />
      )}
    </ElCard>
  )
})
